<?php

namespace app\common\model;

use think\Model;


class PerkLog extends Model
{


    // 表名
    protected $name = 'perk_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    protected $deleteTime = '';

    // 追加属性
    protected $append = [
    ];





    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 用户现金补贴变更
     * */
    public static function perk($money, $user_id, $memo, $type = '', $ids = '')
    {
        $user = model('app\common\model\User')->get($user_id);
        if ($user && $money != 0) {
            $before = $user->perk_money;
            $after = function_exists('bcadd') ? bcadd($user->perk_money, $money, 2) : $user->perk_money + $money;
            //更新会员信息
            $user->save(['perk_money' => $after]);
            //写入日志
            $row = self::create([
                'user_id' => $user_id,
                'perk_money' => $money, // 操作金额
                'before' => $before, // 原金额
                'after' => $after, // 增加后金额
                'memo' => $memo, // 备注
                'type' => $type, // 类型
                'order_id' => $ids // 业务ID
            ]);
            return $row;
        } else {
            return ['code' => 500, 'msg' => '现金补贴变更失败'];
        }
    }
}
